package com.hao.tool.web.module.computer.controller;

import com.hao.tool.common.entity.LayResponse;
import com.hao.tool.web.common.constant.Commons;
import com.hao.tool.web.module.computer.dto.ComputerDTO;
import com.hao.tool.web.module.computer.entity.ComputerInfo;
import com.hao.tool.web.module.computer.service.ApplicationService;
import com.hao.tool.web.module.computer.service.ComputerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * description
 *
 * @author RuiHaoZ on GZ.cmhk
 * @date 2019-11-21 21:47
 */
@RestController
@RequestMapping("/rest/computer")
public class ComputerRestController {
    @Autowired
    private ApplicationService applicationService;
    @Autowired
    private ComputerService computerService;

    @GetMapping("/list")
    public LayResponse list(HttpServletRequest request) {
        String userName = (String) request.getAttribute(Commons.USER_NAME);
        List<ComputerInfo> info = computerService.getByUser(userName);
        if (info != null) {
            return LayResponse.builder().build().setCode(LayResponse.SUCCESS)
                    .setData(info);
        } else {
            return LayResponse.builder().build().setCode(LayResponse.ERROR);
        }
    }


    @PostMapping("/add")
    public LayResponse add(ComputerDTO dto, String userName, HttpServletRequest request) {
        userName = (String) request.getAttribute(Commons.USER_NAME);
        ComputerInfo info = computerService.save(dto, userName);
        return LayResponse.builder().build().setCode(LayResponse.ERROR)
                .setData(info);
    }

    /**
     * @param id
     * @return
     */
    @GetMapping("/get")
    public LayResponse get(Integer id) {
        ComputerInfo info = computerService.getById(id);
        if (info != null) {
            return LayResponse.builder().build().setCode(LayResponse.SUCCESS)
                    .setData(info);
        } else {
            return LayResponse.builder().build().setCode(LayResponse.ERROR);
        }
    }

    /**
     * @param id
     * @return
     */
    @GetMapping("/sh/{id}")
    public String getSh(@PathVariable Integer id) {
        ComputerInfo info = computerService.getById(id);
        if (info != null) {
            List<String> list = new ArrayList<>();
            list.add(info.getIp());
            list.add(info.getUsername());
            list.add(info.getPassword());
            list.add(" ");
            list.add(info.getComName());
            list.add(" ");
            return StringUtils.join(list, " ");
        } else {
            return null;
        }
    }
}
